package com.lanhao.aot.carrierintegration.inpost;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.oned.Code128Writer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;

/**
 * Inpost代理商对接
 * @author kunzhou3
 */
public class InPostProxyUtil {
	private static final Logger LOG = LoggerFactory.getLogger(InPostProxyUtil.class);
	public static final String VER = "1.0";
	public static final String URL = "http://api.cacc-log.com/api/Waybill";
	public static final String Client_Key = "7d1cc6e3-ca8d-4b63-bcfc-6a5630e22cb6";
	public static final String Client_Secret = "25fc3dd9-7042-4729-8451-8db6cb70b721";
	public static final String PROVIDER = "INPOSTR";
	public static final String WAYBILLTYPE = "1";
	public static final String nonDeliveryOption = "RETURN";
	public static final String IMAGE_TYPE = "PDF";
	

	private static Map<String, String> getRequestHeader() {
		Map<String, String> header = new HashMap<>();
		String token = SecureUtil.md5(Client_Key + Client_Secret + VER);
		header.put("version", VER);
		header.put("key", Client_Key);
		header.put("token", token);
		return header;
	}

	public static void doTmsInvoke() {
		JSONObject request = new JSONObject();
		request.put("generateLabelUrl", "true");
		request.put("generateLabel", "true");
//		request.put("width", 2.0);
//		request.put("length", 2.0);
//		request.put("height", 1.0);
		request.put("weight", 0.2);
		
		request.put("customerRefNo", "");
		request.put("imageType", IMAGE_TYPE);
		request.put("nonDeliveryOption", nonDeliveryOption);
		request.put("waybillType", WAYBILLTYPE);
		request.put("provider", PROVIDER);
//		request.put("totalDeclaredValue", 100.0);
		request.put("articleName", "Espace货品");
		request.put("articleEnglishName", "Espace Stuff");
		request.put("weightUnit", "千克");
		request.put("volumeUnit", "英寸");
		request.put("totalDeclaredValueCurrency", "美元");
//		request.put("IossNumber", "IT2309871112");
		
		JSONObject toAddress = new JSONObject();
		toAddress.put("name", "Paweł Smyk");
		toAddress.put("firm", "-");
		toAddress.put("address1", "-");
		toAddress.put("address2", "Ul. Gorzowska 3 D,");
		toAddress.put("countryCode", "PL");
		toAddress.put("city", "Białcz");
		toAddress.put("state", "Lubuskie");
		toAddress.put("zipCode5", "66-460");
		toAddress.put("zipCode4", null);
		toAddress.put("phone", "+48 606 115 604");
//		toAddress.put("email", "abc@abc.com");
		request.put("toAddress", toAddress);
		
		
		JSONObject sendAddress = new JSONObject();
		sendAddress.put("name", "yomu");
  //	sendAddress.put("address1", "");
		sendAddress.put("address1", "Emilii Plater Street 49");
		sendAddress.put("city", "Warszawa");
		sendAddress.put("countryCode", "PL");
		sendAddress.put("phone", "482232888");
		sendAddress.put("state", "Warsaw");
		sendAddress.put("zipCode5", "00-125");
		sendAddress.put("email", "it@anhelogistics.com");
		request.put("sendAddress", sendAddress);
		
//		JSONArray items = new JSONArray();
//		JSONObject item = new JSONObject();
//		item.put("cargoName", "手机贴膜");
//		item.put("hscode", "HS1006");
//		item.put("unit", "只");
//		item.put("qty", 11);
//		item.put("cargoEnglishName", "phone mask");
//		item.put("declaredValue", 2.0);
//		item.put("unitPrice", 0.1);
//		item.put("declaredValueCurrency", "美元");
//		items.add(item);
//		request.put("items", items);
		
		String response = HttpRequest.post(URL).addHeaders(getRequestHeader()).body(request.toJSONString()).execute().body();
		LOG.info("请求InPost，请求参数request={},回结果result={}", request.toJSONString(), response);
		JSONObject responseObject = JSON.parseObject(response);
		int responseCode = responseObject.getIntValue("responseCode");
		if(responseCode == 0) {
			JSONObject resultObject = responseObject.getJSONObject("result");
			boolean success = resultObject.getBooleanValue("isSuccess");
			String waybillNo = resultObject.getString("waybillNo");
			if(success) {
				String fileUrl = resultObject.getString("fileUrl");
				String fileContent = resultObject.getString("fileContent");
				String barCode = resultObject.getString("barCode");
				LOG.info("请求成功，waybillNo={}，fileUrl={}，barCode={}", waybillNo, fileUrl, barCode);
			} else {
				String errorMessage = resultObject.getString("errorMessage");
				LOG.info("请求失败，waybillNo={}，errorMessage={}", waybillNo, errorMessage);
			}
		}
		try {
			FileUtils.write(new File("D:/demo.txt"), response, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void getTmsWaybill(String waybillno) {
		String result = HttpRequest.get("http://api.cacc-log.com/api/Waybill/" + waybillno + "/label")
				.addHeaders(getRequestHeader()).execute().body();
		LOG.info("请求InPost，按照waybillno={}查询result={}", waybillno, result);
		try {
			FileUtils.write(new File("D:/label.txt"), result, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void reGetTmsWaybill(String waybillno) {
		String result = HttpRequest.get("http://api.cacc-log.com/api/Waybill/" + waybillno + "/relabel")
				.addHeaders(getRequestHeader()).execute().body();
		LOG.info("请求InPost，按照waybillno={}重新获取label  result={}", waybillno, result);
		try {
			FileUtils.write(new File("D:/relabel.txt"), result, "UTF-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public static String getTrackingNumber(String barCode) {
		String url = "http://api.cacc-log.com/api/Waybill/TrackingDesc?providerCode=INPOSTR&barCodes=" + barCode;
		String result = HttpRequest.get(url)
				.addHeaders(getRequestHeader()).execute().body();
		LOG.info("请求InPost，按照barCode={}获取跟踪号：result={}", barCode, result);
		
		return result;
	}
	
	public static void diyInPostLabel() {
		try {
			String url = "https://res-oss.anhelogistics.com/image/Inpost_Template.png";
			BufferedImage image = ImageIO.read(new URL(url));
			Graphics2D gd = image.createGraphics();
			gd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			gd.setColor(Color.RED);
			gd.setFont(new Font("黑体", Font.BOLD, 24));
			gd.drawString("7814194032", 1040, 62);
			
			
			int w = 500;// 图片的宽度
			int h = 80;// 图片的高度
			String s = "4320221107143612244";//条形码的内容
			HashMap<EncodeHintType, Object> m = new HashMap<>();//条形码的参数
			m.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
			m.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//条形码的容错率,从小到大是L,M,Q,H,条形码的容错率越高越容易扫描
			m.put(EncodeHintType.MARGIN, 0);//条形码的边框宽度
			Image i = MatrixToImageWriter.toBufferedImage(new Code128Writer().encode(s, BarcodeFormat.CODE_128, w, h, m));//生成条形码的图片
			
			gd.drawImage(i, 400, 170, null);
			
			gd.setColor(Color.BLACK);
			gd.drawString("4320221107143612244", 520, 280);
			
			gd.dispose();
			
			String returnFilePath = "D:/" + UUID.fastUUID().toString(true) + ".png";
			File destFile = new File(returnFilePath);
			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
			ImageIO.write(image, "png", imOut);
			InputStream inputStream = new ByteArrayInputStream(bs.toByteArray());
			OutputStream outStream = new FileOutputStream(destFile);
			IOUtils.copy(inputStream, outStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void diyNewInPostLabel() {
		try {
			String url = "https://res-oss.anhelogistics.com/image/InPost_New_Template.png";
			BufferedImage image = ImageIO.read(new URL(url));
			Graphics2D gd = image.createGraphics();
			gd.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			gd.setColor(Color.RED);
			gd.setFont(new Font("黑体", Font.BOLD, 24));
			gd.drawString("30", 578, 192);
			
			
			String s = "3695457896";//条形码的内容
			
			gd.setColor(new Color(254, 204, 0));
			gd.setFont(new Font("黑体", Font.BOLD, 40));
			gd.drawString(s, 510, 325);
			
			gd.dispose();
			
			String returnFilePath = "D:/" + UUID.fastUUID().toString(true) + ".png";
			File destFile = new File(returnFilePath);
			ByteArrayOutputStream bs = new ByteArrayOutputStream();
			ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
			ImageIO.write(image, "png", imOut);
			InputStream inputStream = new ByteArrayInputStream(bs.toByteArray());
			OutputStream outStream = new FileOutputStream(destFile);
			IOUtils.copy(inputStream, outStream);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public static void doInPostTrackingNoGet() {
		Map<String, String> dataMap = Maps.newHashMap();
		dataMap.put("4320221208172356751", "9761766385");
		dataMap.put("4320221208170815711", "7923152997");
		dataMap.put("4320221207181315119", "9093193992");
		dataMap.put("4320221207163317940", "8410426463");
		dataMap.put("4320221206173822342", "8483077521");
		dataMap.put("4320221206173322329", "1041250253");
		dataMap.put("4320221206163827166", "4343207819");
		dataMap.put("4320221205173316855", "8756836039");
		dataMap.put("4320221201142412355", "5558420159");
		dataMap.put("4320221201142356353", "7315855919");
//		dataMap.put("4320221208164906649", "3284934724");
//		dataMap.put("4320221208164345630", "6990731566");
//		dataMap.put("4320221207182331139", "6939182108");
//		dataMap.put("4320221207181817134", "7277129803");
//		dataMap.put("4320221206173822341", "5962810758");
//		dataMap.put("4320221206170315218", "5260523405");
//		dataMap.put("4320221206164319174", "9175047039");
//		dataMap.put("4320221206164318173", "3068525671");
//		dataMap.put("4320221206161815143", "5685686607");
//		dataMap.put("4320221206160817106", "8632795459");
//		dataMap.put("4320221207181326121", "7388407887");
//		dataMap.put("4320221207162322930", "3525844506");
//		dataMap.put("4320221206172339263", "7082488181");
		
		Set<String> keySet = dataMap.keySet();
		
		for (String wayNo : keySet) {
			String barCode = dataMap.get(wayNo);
			String result = getTrackingNumber(barCode);
			if (StringUtils.isNotBlank(result)) {
				JSONObject object = JSON.parseObject(result);
				String trackingNumber = object.getString("tracking_number");
				String status = object.getString("status");
				if (StringUtils.isNotBlank(trackingNumber)) {
					LOG.info("update eb_task t set t.tracking_no = '{}' where t.mail_no = '{}';", trackingNumber, wayNo);
				}
			}
		}
	}
	
	public static void main(String[] args) {
//		doTmsInvoke();
//		getTmsWaybill("4320221208172356751");
//		reGetTmsWaybill("4320220324184621150");
//		doInPostTrackingNoGet();
		diyNewInPostLabel();
	}
	
}
